package com.sise.cn.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.sise.cn.annotation.AccessAuthority;
import com.sise.cn.constant.CommonConstant;
import com.sise.cn.constant.TimeConstant;
import com.sise.cn.redis.cache.RedisUtil;
import com.sise.cn.utils.SessionContextHolder;
import com.sise.cn.wechat.config.WechatConfig;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName WechatController
 * @Description
 * @Author CCJ
 * @Date 2020/6/2 21:16
 **/
@Slf4j
@RestController
@RequestMapping(value = "/wechat")
public class WechatController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WechatConfig wechatConfig;

    @GetMapping(value = "/login")
    @AccessAuthority
    public void weChatRedirect(HttpServletResponse response) throws IOException {
        log.info("wechatUrlConfig.getUrl()={}", wechatConfig.getCallBackUrl());
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(wechatConfig.getCallBackUrl(), WxConsts.OAUTH2_SCOPE_USER_INFO, null);
        response.sendRedirect(redirectURL);
    }

    /**
     * 微信授权
     *
     * @param code 微信返回的 code 用于获取用户信息
     * @return 页面跳转
     */
    @GetMapping(value = "/callback")
    @AccessAuthority
    public void redirectToIndexPage(@RequestParam("code") String code, HttpServletResponse response, HttpServletRequest request) throws WxErrorException, IOException {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        String token = UUID.randomUUID().toString();
        redisUtil.set(token, JSON.toJSONString(wxMpUser), TimeConstant.ONE_WEEK_SEN);
        Cookie cookie = new Cookie(CommonConstant.COOKIE_TOKEN, token);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
        response.setContentType("application/json;charset=UTF-8");
        response.sendRedirect(wechatConfig.getIndexUrl());
    }

    @RequestMapping(value = "/message", method = {RequestMethod.POST, RequestMethod.GET})
    @AccessAuthority
    public String message(HttpServletRequest request) {
        
//        wxMpService.checkSignature();
        return null;
    }
}
